<template>
  <div class="Index">
    <div class="cont">
      <!-- head -->
      <div class="relative">
        <img src="../assets/img/title.png" class="w-[100%] h-[60px]" alt="">
        <div class="mainbg  h-[23rem] max-h-[23rem] md:h-[43rem] md:max-h-[43rem] w-full flex justify-start items-end ">
          <div class="pb-[3.3rem] pl-[0.9rem]  md:pb-[5rem] md:pl-[3rem]">
            <img src="../assets/img/gamelogo.png" class="w-[5.5rem] max-w-[5.5rem] md:w-[10rem] md:max-w-[10rem]" alt="">
          </div>
        </div>
        <div class=" absolute top-1 right-3" @click="agetitle()">
          <img src="../assets/img/12.png" class="w-[2.5rem]" alt="">
        </div>
      </div>
      <!-- 已登陆显示 -->
      <div id="main">
        <div class="bg-[#805c36] h-[4rem] flex justify-between items-center">
          <div class="pl-2 text-[#FFFFFF] text-[0.8rem]">
            <span>{{ userinfo.name }}</span>
            <span>{{ userinfo.uid }}</span>
          </div>
          <div class="pr-4 text-[#FFFFFF] text-[0.8rem]">
            <span @click="outlogin('确定切换账号？')">切换账号</span>
            <span @click="outlogin('确定退出账号？')" class="w-[2rem] text-center"> 退出</span>
          </div>
        </div>
        <div class="dropdown dropdown-bottom w-full ">
          <label tabindex="0" class=" w-full bg-black " @click="istess = !istess">
            <div class=" flex justify-between items-center h-[4rem]">
              <div class="pl-2">
                <span class="font-bold text-[#fcf6de]" v-if="ifchoose">
                  请先选择服务器
                </span>
                <div class="flex flex-col" v-if="!ifchoose">
                  <div class="font-bold text-[1.2rem] text-[#fcf6de]">{{ gameitem.name }}</div>
                  <div class="text-[0.8rem] text-[#fcf6de]">{{ gameitem.username }}</div>
                </div>
              </div>
              <div class="pr-2">
                <img src="../assets/img/rightbutton.png" class="w-[0.8rem]" alt="">
              </div>
            </div>
          </label>
          <ul tabindex="0" class="dropdown-content  p-2   bg-base-100 w-full" v-if="istess">
            <div class="h-[12rem] overflow-auto mt-2  border-b-1">
              <li v-for="(item, index) in userserverlist" :key="index">
                <div class="flex justify-between " @click="onserverlist(item)">
                  <div class="flex">
                    <div class="font-bold text-[black]">{{ item.server_name }}</div>
                    <div class="w-[1rem] text-[black] text-center">|</div>
                    <div>{{ item.role }}</div>
                  </div>
                  <div class="pr-2" v-if="index == 0">最近登录</div>
                </div>

                <van-divider v-if="index + 1 != userserverlist.length" class="text-[black] " />
              </li>
            </div>
          </ul>
        </div>
        <div class=" h-[4rem] flex justify-between items-center" @click="isserver = !isserver" v-if="false">
          <div class="pl-2">
            <span class="font-bold" v-if="ifchoose">
              请先选择服务器
            </span>
            <div class="flex flex-col" v-if="!ifchoose">
              <div class="font-bold text-[1.2rem]">{{ gameitem.name }}</div>
              <div class="text-[0.8rem]">{{ gameitem.username }}</div>
            </div>
          </div>
          <div class="pr-2">
            <img src="../assets/img/rightbutton.png" class="w-[0.8rem]" alt="">
          </div>
        </div>
        <div v-if="isserver" class="userServer">
          <div class="h-[15rem] overflow-auto mt-4 ">
            <div class="flex justify-center " v-for="(item, index) in userserverlist" :key="index">
              <div class="w-[95%]">
                <div class="flex justify-between " @click="onserverlist(item)">
                  <div class="flex">
                    <div class="font-bold text-[black]">{{ item.server_name }}</div>
                    <div class="w-[1rem] text-[black] text-center">|</div>
                    <div>{{ item.role }}</div>
                  </div>
                  <div class="" v-if="index == 0">最近登录</div>
                </div>
                <van-divider v-if="index + 1 != userserverlist.length" class="text-[black]" />
              </div>
            </div>
          </div>
          <!-- userserverlist -->
        </div>
        <!-- <van-collapse v-model="activeNames" ref="collapse" v-if="false">
          <van-collapse-item name="1">
            <template #title>
              <div>
                <span class="font-bold" v-if="ifchoose">
                  请先选择服务器
                </span>
                <div class="flex flex-col" v-if="!ifchoose">
                  <div class="font-bold text-[1.2rem]">{{ gameitem.name }}</div>
                  <div class="text-[0.8rem]">{{ gameitem.username }}</div>
                </div>
              </div>
            </template>
          </van-collapse-item>
        </van-collapse> -->
        <div class="flex justify-center items-center mt-4 mb-2" v-if="ifchoose">
          <img src="../assets/img/noserver.jpg" class="w-[15rem]" alt="">
        </div>

      </div>
      <!-- 游戏商品列表 -->
      <div class="product_list flex justify-center" v-if="!ifchoose">
        <div class="w-[98%] flex justify-center gap-[0.2rem] flex-wrap mt-7 mb-9">
          <!-- <van-badge>
            <div class="child"  />
            <template #content>
              <van-icon name="success" class="badge-icon" />
            </template>
          </van-badge> -->
          <div v-for="(item, index) in proplist" @click="propselect(item)" class="relative">
            <div v-if="item.present != '0'"
              class="px-1 h-[1.2rem] proptitlebg absolute text-[0.8rem] text-center text-white ">
              <span>赠送{{ item.present }}%</span>
            </div>
            <div class=" rounded-lg bg-[#fdf6dc] border border-[#8f714e] w-[7rem] h-[10rem] mt-2 flex justify-center items-center flex-col">
              <!-- {{ item.propname }} -->
              <img :src="imgproplist[`${item.img_id}`]" class="w-[4rem] h-[4rem]" alt="道具图片">
              <div class="mt-4 text-[0.8rem]">{{ item.name }}</div>
              <div class="mt-4">
                <button :class="selectindex == item.id ? 'selectstylebut' : ''"
                  class="bg-[#dddcdc] w-[6rem] rounded-xl text-[#865931]">￥{{ item.price }}</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 充值说明 -->
      <div class="cz_explain border flex justify-center" v-if="!ifchoose">
        <div class="explain_box w-[95%] mt-9 mb-9">
          <div class=" rounded-lg border border-[#9d9d9d] w-full py-1 bg-[rgb(246,246,246)]">
            <div class="text-[#865931] pt-2">【充值说明】</div>
            <div class="mt3-top flex flex-col justify-center w-[95%] ml-3 mt-3 gap-1">
              <div class="text-[0.9rem] text-[#865931]">尊敬的冒险者，欢迎您来到《我叫MT：经典再现》游戏商城!</div>
              <div class="text-[0.9rem] text-[#865931]">商城中的晶石可用于在游戏内购买所有商品。购买之前请留意您的晶石数量。购买晶石后系统将会1分钟内发放到您游戏晶石商品栏，请注意查收。</div>
              <div class="text-[0.9rem] text-[#865931]">目前商城仅支持从iOS官方商店、官网等游戏官方渠道、Tap渠道、好游快爆渠道下载游戏的玩家购买。</div>
              <div class="text-[0.9rem] text-[#865931]">如遭遇充值相关问题，请您：</div>
              <div class="text-[0.9rem] text-[#865931]">联系官方客服QQ：2885346628 (服务时间9:00~22:00)</div>
            </div>

          </div>
          <!-- 充值提醒-->
          <div class="mt-2 text-[0.7rem]">
            <van-icon name="question" color="rgb(133,133,133)" />请适度娱乐，理性消费。活动最终解释权归《我叫MT：经典再现》手游官方团队所有。
          </div>
        </div>
      </div>
      <van-sticky :offset-bottom="0" position="bottom" v-if="!ifchoose">
        <div class="w-full h-[5rem] flex justify-center items-center bg-white zfbg">
          <div v-if="ispropstore"
            class=" rounded-3xl w-[21rem] h-[2.8rem] bg-[rgb(134,89,49)] flex justify-center items-center text-[#ffffff]"
            @click="isshow = true">
            立即支付￥{{ zfje }}</div>
          <div v-if="!ispropstore"
            class=" rounded-3xl w-[21rem] h-[2.8rem] bg-[#DDDCDC] flex justify-center items-center text-[rgb(158,158,158)]">
            请选择充值金额</div>
        </div>
      </van-sticky>
      <!-- 弹框 -->
      <van-overlay :show="isshow" z-index=100 :lock-scroll=true>
        <div class="flex justify-center items-end h-full">
          <div class="flex flex-col w-full">
            <div class="flex justify-end">
              <img src="../assets/img/gb.png" class="w-[1.5rem] mr-2  mb-1" alt="关闭" @click="isshow = false">
            </div>
            <div class="w-full h-[24rem] bg-white  rounded-t-xl">
              <div class="flex justify-center h-[3rem] items-center font-bold zffs">
                <span>选择支付方式</span>
              </div>
              <div class=" flex justify-center">
                <!-- 物品内容 -->
                <div class="w-[90%] h-[9rem] bg-[rgb(229,229,229)] mt-5 rounded-lg">
                  <div>
                    <div class="ml-3 mt-3">
                      <span class=" font-bold">{{ propname }}</span>
                    </div>
                    <div class="ml-3 mt-3 flex justify-between text-[0.9rem]">
                      <div>充值账号:</div>
                      <div class="pr-2 text-[#7B7B7B]"><span>{{ gameitem.name }}</span> | <span>{{ gameitem.username
                      }}</span></div>
                    </div>
                    <van-divider :style="{ color: '#9D9D9D', borderColor: '#9D9D9D', padding: '0 16px' }">
                    </van-divider>
                    <div class="flex justify-end mr-5">
                      <div><span class=" font-bold">合计：</span><span class="text-[#865931] font-bold">￥{{ zfje
                      }}</span></div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex justify-center mt-5">
                <div class="w-[90%] border border-[#865931] h-[3rem] rounded-xl">
                  <div class="flex h-full justify-between items-center">
                    <div class="flex">
                      <img src="../assets/img/wx.png" class=" mx-2 w-[2rem] h-[1.8rem]" alt=""> <span>微信支付</span>
                    </div>
                    <div>
                      <img src="../assets/img/yd.png" class="w-[1.5rem] h-[1.5rem] mr-3" alt="">
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex justify-center mt-5">
                <div class="w-full h-[5rem] flex justify-center items-center bg-white">
                  <div v-if="wxzfloading"
                    class=" rounded-3xl w-[21rem] h-[2.8rem] bg-[rgb(134,89,49)] flex justify-center items-center text-[white]"
                    @click="zffun()">
                    <span class="text-[#ffffff]"> 立即支付￥{{ zfje }}</span>
                  </div>
                  <div v-if="!wxzfloading"
                    class=" rounded-3xl w-[21rem] h-[2.8rem] bg-[rgb(230,87,7)] flex justify-center items-center text-[white]">
                    <van-loading />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </van-overlay>
      <van-dialog v-model:show="wxzfsuccess" title="充值成功">
      <div class="flex justify-center"> 将在一分钟内发送到游戏内</div>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import md5 from 'js-md5';
import { mapState, mapActions } from 'pinia'
import { useCounterStore } from '../stores/counter'
import wx from 'weixin-jsapi'
import imga from '../assets/img/prop/6.png'
import imgd from '../assets/img/prop/30.png'
import imgf from '../assets/img/prop/98.png'
import imgg from '../assets/img/prop/128.png'
import imgk from '../assets/img/prop/328.png'
import imgu from '../assets/img/prop/648.png'
import { mapStores } from 'pinia'

export default {
  data() {
    return {
      testimgpath:'',
      wxzfsuccess: false,//支付成功弹框
      wxzfloading: true, //立即支付loading
      istess: 'true',
      wxzfdata: '',
      selectindex: '',
      ispropstore: false,
      propname: '60宝箱x1',
      isshow: false,
      isserver: false,
      // 道具
      proplist: [
        {
          propname: '上古神星',
          propmoney: '6',
          present: '100',
          img_id:6
        },
        {
          propname: '上古神星1',
          propmoney: '12',
          present: '0'
        },
        {
          propname: '上古神星2',
          propmoney: '18',
          present: '0'
        },
        {
          propname: '上古神星3',
          propmoney: '24',
          present: '0'
        }, {
          propname: '上古神星',
          propmoney: '6',
          present: '0'
        },
        {
          propname: '上古神星1',
          propmoney: '12',
          present: '0'
        },
        {
          propname: '上古神星2',
          propmoney: '18',
          present: '0'
        },
        {
          propname: '上古神星3',
          propmoney: '24',
          present: '0'
        }
      ],
      // 支付金额
      zfje: '',
      ifchoose: true, // 是否已经选择区服
      // 已经选择的区服信息
      gameitem: {
        gid: '',
        name: '',
        username: ''
      },
      activeNames: [0],
      serverlist: [
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },
        {
          server_name: '服务器',
          role: '2233'
        },

      ],
      userserverlist:'',
      // 
      userinfo: {
        name: '你好,',
        uid: localStorage.getItem('userid')
      },
      imgproplist:{
        6: imga,
        30: imgd,
        98: imgf,
        128: imgg,
        328: imgk,
        648: imgu,
        1000:imgu,
        3000:imgu,
        5000:imgu,
        10000:imgu
      }
      // 
    }
  },
  computed: {
 
    ...mapState(useCounterStore, ['gid', 'path'])
  },
  created() {
   
    this.getwxdata()
    this.getserverlist()
   
    // this.getproplist('48')
  },  
  methods: {
    
    getserverlist(){
      let signmd5 = md5(`user_token=${localStorage.getItem('token')}&timestamp=${Date.parse(new Date())}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
      this.$http({
        method: 'post',
        url:`${this.path}/api/mtstore/role`,
        data:qs.stringify({
          user_token: localStorage.getItem('token'),
          timestamp:Date.parse(new Date()),
          sign:signmd5.toUpperCase()
        })
      }).then(res => {

        if(res.data.status == '200'){
          this.userserverlist = res.data.data.role_list
          
        }else if (res.data.status == '1004'){
          localStorage.removeItem("token");
          localStorage.removeItem("code");
          localStorage.removeItem("state");
          // this.$router.push('/')
          let e = `${this.path}/api/wx/GetOpenId?gid=${this.gid}`
          window.location.href = e
        }else{
          // this.userserverlist = this.serverlist
          this.$toast.fail(`错误${res.data.message}`);
        }
      }).catch( res =>{
        console.log(res)
      })
    },
    getwxdata() {
      this.$http({
        method: 'get',
        url: `${this.path}/api/wx/GetWxConfig?gid=${this.gid}`,
      }).then(res => {
        this.wxzfdata = res.data.data
        console.log('获取微信支付数据', res)
      })
    },
    zffun() {
      // loading
      this.wxzfloading =false
      var $this = this
      let zfsign = md5(`user_token=${localStorage.getItem('token')}&timestamp=${Date.parse(new Date())}&server_id=${this.gameitem.sid}&role_id=${this.gameitem.roleid}&product_id=${this.selectindex}&gid=${this.gameitem.gid}&game_role_name=${this.gameitem.username}&amount=${this.zfje}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
      this.$http({
        method: 'post',
        url: `${this.path}/api/mtstore/createorder`,
        data: qs.stringify({
          user_token: localStorage.getItem('token'),
          gid: this.gameitem.gid,
          role_id: this.gameitem.roleid,
          product_id: this.selectindex,
          server_id: this.gameitem.sid,
          amount: this.zfje,
          game_role_name: this.gameitem.username,
          timestamp: Date.parse(new Date()),
          sign: zfsign.toUpperCase()
        })
      }).then(res => {
        console.log('wxdata', res)
        if (res.data.status == '200') {
          // 调用微信支付
          let wxdata = res.data.data.params
          wx.config({
            // debug: true,//这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
            appId: this.wxzfdata.appId,
            timestamp: this.wxzfdata.timestamp,
            nonceStr: this.wxzfdata.nonceStr,
            signature: this.wxzfdata.signature,
            paySign: wxdata.sign,
            jsApiList: ['chooseWXPay']
          })
          wx.ready(function () {
            console.log('进入ready')
            wx.chooseWXPay({
              appId: wxdata.appid,
              timestamp: wxdata.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: wxdata.nonceStr, // 支付签名随机串，不长于 32 
              package: wxdata.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: wxdata.sign, // 支付签名
              success: function (res) {
                console.log('支付成功')
                $this.isshow = false //支付弹框
                $this.wxzfsuccess = true
                setTimeout(() => {
                  $this.wxzfsuccess = false
                }, 3000);
              },
              cancel: function (res) {
                $this.$toast.fail('已取消支付');
              },
              fail: function (res) {
                $this.$toast.fail('支付失败，请重试');
              }
            })
            this.wxzfloading = true
          })
          this.wxzfloading = true
        } else {
          $this.$toast.fail(`${res.data.message}支付失败！`);
          this.wxzfloading = true
        }
      }).catch(res => {
        this.wxzfloading = true
        console.log('https:/接口错误！！')
      })
    },
    ...mapActions(useCounterStore, ['increment']),
    onserverlist(item) {
      this.istess = false
      console.log('itemlist', item)
      // 关闭折叠面板，改变显示区服信息，关闭请选择服务器提示
      // this.$refs.collapse.toggleAll()//关闭手风琴状态
      this.ifchoose = false
      this.isserver = false
      this.gameitem.gid = item.gid
      this.gameitem.name = item.server_name
      this.gameitem.username = item.role
      this.gameitem.roleid = item.roleid
      this.gameitem.sid = item.sid
      // get prop
      this.getproplist(item.gid)
    },
    getproplist(item) {
      // 获取商品数据接口
      let propsign = md5(`user_token=${localStorage.getItem('token')}&timestamp=${Date.parse(new Date())}&gid=${item}&key=N5Gp6yTpl1WybuQZ0MnbEVgZ2mKOlfRE`)
      this.$http({
        method: 'post',
        url: `${this.path}/api/mtstore/goodslist`,
        data: qs.stringify({
          user_token: localStorage.getItem('token'),
          gid: item,
          timestamp: Date.parse(new Date()),
          sign: propsign.toUpperCase()
        })
      }).then(res => {
        // let itemproplist = []
        // for (let index = 0; index < res.data.data.length; index++) {
        //   const element = res.data.data[index];
        //   console.log(element)
        //   if(element.img_id == '48'){
        //     // element.
        //   }
        //   itemproplist.push()
        // }
        this.proplist = res.data.data
        console.log('propslist', res)
      })
    },
    propselect(item) {
      console.log('点击了商品', item)
      this.zfje = item.price // 商品金额
      this.selectindex = item.id //商品id
      this.propname = item.name// 商品名称
      this.ispropstore = true
    },
    // 退出登陆||切换用户
    outlogin(item) {
      this.$dialog.confirm({
        title: item,
        // message: '弹窗内容',
      })
        .then(() => {
          localStorage.removeItem("token");
          localStorage.removeItem("code");
          localStorage.removeItem("state");
          // this.$router.push('/')
          let e = `${this.path}/api/wx/GetOpenId?gid=${this.gid}`
          window.location.href = e
          // 清除用户数据
        })
        .catch(() => {
          // on cancel
        });

    },
    // 年龄提示
    agetitle() {
      this.$dialog.alert({
        messageAlign: 'left',
        title: '适龄提示',
        message: '1、本游戏是一款策略放置类手机游戏，适用于年满12周岁及以上的用户，建议未成年人在家长监护下使用游戏产品。\n2、本游戏以《我叫MT》相关故事为背景，角色3D形象清新可爱，技能特效华丽酷炫。游戏画面丰富美好、配乐欢快、搭建各种强力宠物伙伴组合，采用不间断的自动战斗模式。挑战各种动画中的劲敌和怪物，探索MT的世界。\n3、本游戏中有用户实名认证系统，认证为未成年人的用户将接受以下管理:游戏中部分玩法和道具需要付费。未满8周岁的用户不能付费; 8周岁以上未满16周岁的未成年人用户，单次充值金额不得超过50元人民币，每月充值金额累计不得超过200元人民币; 16周岁以上的未成年人用户，单次充值金额不得超过100元人民币，每月充值金额累计不得超过400元人民币。未实名账号不能登录游戏。未成年玩家可在周五、周六、周日和法定节假日每日晚20时至21时登录游戏，其他时间无法登录游戏。\n4、游戏闯关对战过程中要求玩家综合考虑技能搭配、属性克制、职业特性等。对出场的伙伴及天赋选择进行策略安排。可以锻炼玩家的逻辑思维能力;设计多种玩法副本，给玩家带来丰富体验。',
      }).then(() => {
        // on close
      });
    },

  }
}
</script>

<style scoped>
.Index{
  width: 100%;
  height: 100vh;
  background: url(../assets/img/logoBg.png) no-repeat center center;
  background-size: cover;
  overflow: auto;
}

.dropdown-content{
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  box-shadow: inset 0px 0px 14px #d7d7d7;
}

.selectstylebut {
  background-color: #865931;
  color: white;
}

.zfbg {
  box-shadow: 0px -2px 10px rgba(133, 133, 133, 0.9)
}

.zffs {
  box-shadow: 0px 1px 1px rgba(133, 133, 133, 0.9)
}

.mainbg {
  background: url(../assets/img/headbg.png) no-repeat;
  /* background-size: cover; */
  background-size: 100% 100%;
}
.cz_explain{
  border-width:0;
}
.rounded-lg{
  border-radius: 20px;
  background: #fff;
}
.proptitlebg {
  background: url(../assets/img/proptitle.png) no-repeat;
  background-size: 100% 100%;
}
.userServer{
  z-index: 999;
}
.mt3-top{
  margin-top: 0;
}
</style>
